package com.bluefish.bltuan.interceptor;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bluefish.bltuan.annotation.RequireLogin;
import com.bluefish.bltuan.tools.ActionUtil;
import com.bluefish.bltuan.tools.annotation.StringUtil;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class LoginInterceptor implements Interceptor {

	private static final String TO_OPEN_LOGIN = "toOpenLogin";

	private static final String TO_ADMIN_LOGIN = "toAdminLogin";

	private static final String ADMIN = "/admin";
	
	private static final String PERSONAL = "/personal";

	private static Logger log = LoggerFactory.getLogger(LoginInterceptor.class);
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void destroy() {

	}

	public void init() {

	}

	public String intercept(ActionInvocation ai) throws Exception {
		if (isCurrentActionNeedLogin(ai) && !alreadyLogin()) {
			log.info("current action need login but current user is not login yet");
			String uri = ActionUtil.getHttpRequest().getServletPath();
			return uri.startsWith(ADMIN) || uri.startsWith(PERSONAL)? TO_ADMIN_LOGIN : TO_OPEN_LOGIN;
		}
		return ai.invoke();
	}

	private boolean isCurrentActionNeedLogin(ActionInvocation ai)
			throws SecurityException, NoSuchMethodException {
		String method = ai.getProxy().getMethod();
		Object action = ai.getAction();
		Method mtd = action.getClass().getMethod(method, (Class[]) null);

		if (mtd.isAnnotationPresent(RequireLogin.class)) {
			return true;
		}
		if (action.getClass().isAnnotationPresent(RequireLogin.class)) {
			Annotation an = action.getClass().getAnnotation(RequireLogin.class);
			String[] excludes = ((RequireLogin) an).exclude();
			return !StringUtil.contains(excludes, method);
		}
		return false;
	}

	private boolean alreadyLogin() {
		return ActionUtil.online();
	}

}
